/*
 * init.c
 *
 *  Created on: 2009-5-5
 *      Author: tian
 */

#include"tcpipsim.h"
#include<stdio.h>
#include<string.h>

int init(){
	char addr[16]={0};
	/*Initialize ip address*/
	printf("TCP/IP stack simulation initialize begin\n");
	printf("Step 1:please input the ip address of this stack\n");
	scanf("%s",addr);
	if(inet_aton(addr,&my_ip_addr)<0){
		fprintf(stderr,"%s not a valid ip address",addr);
		return -1;
	}

	/*Initialize message queue*/
	printf("Step 2:get the message queue of this stack\n");
	my_msgqid=msgget(IPC_PRIVATE,IPC_CREAT|0666);
	if(my_msgqid<0){
		perror("cannot create a message queue");
		return -1;
	}
	printf("this stack's message queue identifier is %d,\n",my_msgqid);
	printf("you must remember this identifer so that you\n");
	printf("can add it to other stacks to communicate\n");

	/*Initialize route list*/
	printf("Step 3:set ip route list\n");
	int i=0;
	char answer=0;
	//struct in_addr peer_ip_addr;
	for(;i<MAX_ROUTE_NODE_NUM;i++){
		memset(&(routelst[i].ip_addr),0,sizeof(struct in_addr));
		routelst[i].msgqid=-1;
	}
	printf("set default gateway\n");
	printf("please input gateway ip address:\n");
	scanf("%s",addr);
	if(inet_aton(addr,&(routelst[0].ip_addr))<0){
			fprintf(stderr,"%s not a valid ip address",addr);
			return -1;
	}
	printf("please input gateway message queue identifier:\n");
	scanf("%d",&(routelst[0].msgqid));
	getchar();
	for(i=1;i<MAX_ROUTE_NODE_NUM;i++){
		printf("do you want to set another tcp/ip stack?(y/n)\n");
		scanf("%c",&answer);
		if(answer=='n'||answer=='N')
			break;
		else if(answer=='y'||answer=='Y'){
			printf("please input peer stack's ip address:\n");
			scanf("%s",addr);
			if(inet_aton(addr,&(routelst[i].ip_addr))<0){
					fprintf(stderr,"%s not a valid ip address",addr);
					return -1;
			}
			printf("please input its message queue identifier:\n");
			scanf("%d",&(routelst[i].msgqid));
			getchar();
		}
		else{
			i--;
		}
	}

	printf("Initialize end.\n");
	printf("now this tcp/ip stack begin to work\n");
	return 0;
}
